<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="编码名" prop="name">
        <treeselect style="width: 300px" v-model="queryParams.bmId" :options="realTree" :normalizer="bmNormalizer"
                    @select="querySelectName" placeholder="选择编码名"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['sysBmType:sysBmType:add']"
        >新增
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="warning"-->
      <!--          plain-->
      <!--          icon="el-icon-upload"-->
      <!--          size="mini"-->
      <!--          @click="handleImport"-->
      <!--          v-hasPermi="['sysBmType:sysBmType:import']"-->
      <!--        >导入-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="handleImport"
          v-hasPermi="['sysBmType:sysBmType:import']"
        >导入
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="sysBmTypeList"
      row-key="bmId"
      default-expand-all
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="编码名" prop="name"/>
      <el-table-column label="编码字母" align="center" prop="value"/>
      <el-table-column label="组成编码" align="center" prop="genCode"/>
      <el-table-column label="层级" align="center" prop="hierarchy"/>
      <!--      <el-table-column label="父级" align="center" prop="parentId" />-->
      <!--      <el-table-column label="等级" align="center" prop="lv" />-->
      <!--      <el-table-column label="当前索引" align="center" prop="code" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['sysBmType:sysBmType:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['sysBmType:sysBmType:add']"
          >新增
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['sysBmType:sysBmType:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 抄表导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <!--<el-checkbox v-model="upload.updateSupport" />是否更新已经存在的数据-->
          <!--<el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>-->
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改编码配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="编码名" prop="name">
          <el-input v-model="form.name" placeholder="请输入编码名"/>
        </el-form-item>
        <el-form-item label="编码字母" prop="value">
          <el-input v-model="form.value" placeholder="请输入编码字母"/>
        </el-form-item>
        <el-form-item label="父级" prop="parentId">
          <treeselect v-model="form.parentId" :options="sysBmTypeOptions" :normalizer="normalizer" placeholder="请选择父级"
                      @select="treeSelectFn"/>
        </el-form-item>
        <!--        <el-form-item label="等级" prop="lv">-->
        <!--          <el-input v-model="form.lv" placeholder="请输入等级" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="当前索引" prop="code">-->
        <!--          <el-input v-model="form.code" placeholder="请输入当前索引" />-->
        <!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 抄表导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <!--<el-checkbox v-model="upload.updateSupport" />是否更新已经存在的数据-->
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import {
  listSysBmType,
  getSysBmType,
  delSysBmType,
  addSysBmType,
  updateSysBmType,
  exportSysBmType
} from '@/api/system/sysBmType'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {getToken} from '@/utils/auth'
import {downloadCheckMeter1} from '@/api/smartParks/energy/energyMeterRading'

export default {
  name: 'SysBmType',
  components: {
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      realTree: [],//暂存原始树
      code: '',
      codeName: '',
      clType: '',
      resultItem: null,
      // 编码配置表格数据
      sysBmTypeList: [],
      // 编码配置树选项
      sysBmTypeOptions: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 用户导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/system/sysBmType/importData'
      },
      // 查询参数
      queryParams: {
        name: null,
        value: null,
        parentId: null,
        lv: null,
        code: null
      },
      // 表单参数
      form: {},
      selectItem: null,
      // 表单校验
      rules: {}
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询编码配置列表 */
    async getList() {
      this.realTree = []
      this.loading = true;
      await listSysBmType(this.queryParams).then(response => {
        let tree = this.handleTree(response.data, "bmId", "parentId");
        this.sysBmTypeList = tree;
        const data = {bmId: 0, name: '顶级节点', children: []};
        data.children = this.deepClone(tree);
        //深拷贝储存原始数据
        this.realTree.push(data)
        console.log("原始树", this.realTree)
        this.$store.commit("SET_BMTREE", this.deepClone(this.sysBmTypeList))
        this.loading = false;
      });
    },
    /** 转换编码配置数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.bmId,
        label: node.name,
        children: node.children
      };
    },
    //同步等待获取到树
    async getTreeselect() {
      await listSysBmType().then(response => {
        let resData = response.data
        let tree = this.handleTree(resData, "bmId", "parentId");
        this.sysBmTypeOptions = [];
        this.realTree = []
        const data = {bmId: 0, name: '顶级节点', children: []};
        data.children = tree
        let deepData = this.deepClone(data)
        this.realTree.push(deepData)
        this.sysBmTypeOptions.push(data);
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "抄表导入";
      this.upload.open = true;
    },
    treeSelectFn(node) {
      this.selectItem = this.deepClone(node)
      if (node.bmId == 0) {
        this.form.lv = 1
        this.form.parentId = 0
      } else {
        this.form.parentId = node.bmId
        this.form.lv = node.lv + 1
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        bmId: null,
        name: null,
        value: null,
        parentId: null,
        createTime: null,
        updateTime: null,
        lv: null,
        code: null,
        genCode: null,
        resultItem: null,
        hierarchy: null
      };
      this.resetForm("form");
    },
    querySelectName(item) {
      this.queryParams.bmId = item.bmId
    },
    /** 搜索按钮操作 */
    async handleQuery() {
      let realTree = this.deepClone(this.realTree)
      await this.getList();
      this.realTree = realTree
      this.$store.commit("SET_BMTREE", realTree[0].children)
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        name: null,
        value: null,
        parentId: null,
        lv: null,
        code: null,
        bmId: null
      }
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.bmId) {
        this.form.parentId = row.bmId;
        this.form.lv = row.lv + 1
        this.clType = "edit"
      } else {
        this.clType = "add"
        this.form.parentId = 0;
        this.form.lv = 1
      }
      this.open = true;
      this.title = "添加编码配置";
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      //等待获取新树
      await this.getTreeselect();
      if (row != null) {
        this.form.parentId = row.bmId;
        this.form.lv = row.lv + 1
      }
      this.clType = "edit"
      await getSysBmType(row.bmId).then(response => {
        this.form = response.data;
        //删除子级节点，不让选择该节点以及该节点的子节点，顾删除子级
        this.delChilds(this.sysBmTypeOptions, row.bmId)
        console.log('realTree delAfter', this.realTree)
        this.open = true;
        this.title = "修改编码配置";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let hierarchy = ""
          let node = this.form

          if (this.isEmpty(node.bmId)) {
            //新增s
            if (this.form.parentId == 0 || this.form.parentId == '0') {
              this.form.genCode = this.form.value
            }
            let node = this.form
            if (node.parentId == '' || node.parentId == 0 || node.parentId == '0') {
              this.resultCode = node.value
            } else {
              this.code = ''
              this.codeName = ''
              this.genCodeFn(node, this.realTree)
              this.code += this.resultItem.value
              this.codeName += this.resultItem.name
              let strArr = this.code.split('-')
              let strArrName = this.codeName.split('-')
              strArr = strArr.reverse()
              strArrName = strArrName.reverse()
              let resultStr = strArr.toString().replaceAll(',', '-')
              hierarchy = strArrName.toString().replaceAll(',', '-')
              this.resultCode = resultStr
              this.resultItem = null
            }

            this.form.genCode = this.resultCode
            this.form.hierarchy = hierarchy
            if (this.form.lv == 1) {
              this.form.hierarchy = this.form.name
            }

            addSysBmType(this.form).then(response => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
            //新增e
          } else {
            //修改 s
            this.code = ""
            this.codeName = ""
            let realTree = this.deepClone(this.realTree)
            //在原始树里获取到当前选择节点
            this.treeFindById(realTree, node.bmId)
            let resNode = this.resultItem
            resNode.name = node.name
            resNode.value = node.value
            this.resultItem = null
            console.log("resNode", resNode)
            //1.先删除树里面的当前节点
            this.delChilds(realTree, resNode.bmId)
            //2.把当前节点移动到所选位置的下面,并更改parentId
            console.log('所选节点', this.selectItem)
            let selectItem = null
            //未改变父级的情况
            if (this.isEmpty(this.selectItem)) {
              this.treeFindById(realTree, resNode.parentId)
              selectItem = this.resultItem
            } else {
              this.treeFindById(realTree, this.selectItem.bmId)
              selectItem = this.resultItem
              // 更改parentId
              resNode.parentId = selectItem.bmId
              resNode.lv = parseInt(selectItem.lv) + 1
            }

            if (this.isEmpty(selectItem.children)) {
              selectItem.children = []
            }
            selectItem.children.push(resNode)
            //3.生产所选节点以及所选节点子级的编码，并添加到修改项editList
            this.editList = []
            this.genEditSubmitCode(resNode, realTree)
            this.selectItem = null
            console.log(this.editList)
            updateSysBmType(this.editList).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
            //修改 e
          }

        }
      });
    },
    //删除tree的节点
    delChilds(treeList, id) {
      if (!treeList || !treeList.length) {
        return
      }
      for (let i = 0; i < treeList.length; i++) {
        // console.log(treeList[i].bmId, id)
        if (treeList[i].bmId == id) {
          treeList.splice(i, 1);
          break;
        }
        this.delChilds(treeList[i].children, id)
      }
    },
    genEditSubmitCode(item, tree) {
      console.log("genEditSubmitCode", item)
      let hierarchy = ""
      this.code = ""
      this.codeName = ""
      this.genCodeFn(item, tree)
      if (this.isEmpty(this.resultItem)) {
        return
      } else {
        this.code += this.resultItem.value
        this.codeName += this.resultItem.name
        let strArr = this.code.split("-")
        let strArrName = this.codeName.split("-")
        strArr = strArr.reverse()
        strArrName = strArrName.reverse()
        let resultStr = strArr.toString().replaceAll(',', '-')
        hierarchy = strArrName.toString().replaceAll(',', '-')
        this.resultCode = resultStr
        this.resultItem = null
        item.genCode = this.resultCode
        item.hierarchy = hierarchy
        if (item.lv == 1 || item.parentId == '0' || item.parentId == 0) {
          item.hierarchy = item.name
          item.genCode = item.value
        }

        console.log("hierarchy", hierarchy)
        this.editList.push(item)
        if (!this.isEmpty(item.children) && item.children.length > 0) {
          item.children.forEach(item2 => {
            this.genEditSubmitCode(item2, tree)
          })
        }
      }
    },
    genCodeFn(node, tree) {
      let parent = ''
      if (!this.isEmpty(node)) {
        parent = node.parentId
      }
      if ((parent == '' || parent == '0' || parent == 0)) return;
      this.code += `${node.value}-`
      this.codeName += `${node.name}-`
      this.resultItem = null
      this.treeFindById(tree, parent)
      this.genCodeFn(this.resultItem, tree)
    },
    treeFindById(tree, bmId) {
      if (this.isEmpty(tree)) return
      tree.forEach(item => {
        if (item.bmId == bmId) {
          this.resultItem = item
          return
        }
        if (!this.isEmpty(item.children)) {
          this.treeFindById(item.children, bmId)
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除编码配置编号为"' + row.bmId + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delSysBmType(row.bmId);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
// 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },

    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
}
</script>
